﻿using System;
using System.Data;
using System.IO;
using System.Text;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using RabbitMQ.Client;
using MongoDB.Bson;
using MongoDB.Driver;
using MyFramework.DB;
using MyFramework.Domain.Model;

namespace MyFramework.MQ
{
    class Program
    {
        private static MongoClient client = null;
        static void Main(string[] args)
        {
            try
            {
                client = MongoDBContext.GetInstance();
            }
            catch (Exception e)
            {
                client = new MongoClient(@"mongodb://192.168.123.49:27017");
                Console.WriteLine(@"从json文件获取mongodb连接失败!启用默认配置！");
            }
              
                var qName = "logging";
                var exchangeName = "logexchange";
                var exchangeType = "fanout";//topic、fanout
                var routingKey = "*";
                var uri = new Uri("amqp://192.168.123.49:5672/");
                var factory = new ConnectionFactory
                {
                    UserName = "terrydash",
                    Password = "xgxxgx",
                    RequestedHeartbeat = 0,
                    Endpoint = new AmqpTcpEndpoint(uri)
                };
                using (var connection = factory.CreateConnection())
                {
                    using (var channel = connection.CreateModel())
                    {
                        channel.ExchangeDeclare(exchangeName, exchangeType);
                        channel.QueueDeclare(qName, true, false, false, null);
                        channel.QueueBind(qName, exchangeName, routingKey);
                        //定义这个队列的消费者
                        //false为手动应答，true为自动应答
                        
                        bool noAck = false;
                        while (true)
                        {
                           
                            BasicGetResult result = channel.BasicGet(qName, noAck);
                            
                            if (result != null)
                            {
                                byte[] bytes = result.Body;
                                var messageStr = Encoding.UTF8.GetString(bytes);
                                Log log = null;
                                try
                                {
                                    log = JsonConvert.DeserializeObject<Log>(messageStr);
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine("传输的日志格式不正确格式");

                                }
                                finally
                                {
                                Console.WriteLine("Receive a Message:" + messageStr);
                                }
                                if (log != null)
                                {
                                    Insert(log);
                                    

                                    //如果是自动应答，下下面这句代码不用写啦。
                                    channel.BasicAck(result.DeliveryTag, false);
                                }
                            
                        }


                        }
                    }
                }
            
           
        }

        static void Insert(Log log)
        {
            var programname = string.IsNullOrEmpty(log.ProgramInfo.Name)
                ? "default"
                : log.ProgramInfo.Name;            
            programname += "_V"+log.ProgramInfo.Version;
            programname = programname.Replace(".", "_");
            var database = client.GetDatabase(programname);
            var collection = database.GetCollection<BsonDocument>("logging");
            collection.InsertOne(log.ToBsonDocument());
            
        }
      
    }
}
